//
//  MallOrderList.swift
//  LeGou
//
//  Created by lxm on 2022/8/5.
//

import Foundation
import HandyJSON
import UIKit


class ProfitList: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {
    //MARK: --------------------属性--------------------
    var listData = [MineModels.ProfitList]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    var status : ProfitState = .all
    
    var type : ProfitIndexType = .buySelf
    //MARK: --------------------UI控件--------------------
    let tableView = UITableView().then { t in
        t.separatorStyle = .none
        t.tableFooterView = UIView()
    }
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        tableView.mj_header?.beginRefreshing()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        setUpTableView()
        view.backgroundColor = "#F5F5F5".zm.hex()
        if type == .auction {
            title = "竞购收益"
        } else if type == .hammer {
            title = "竞购收益"
        }
    }
    
    func setUpTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        tableView.zm.register(nibName: "PorfitListCell", reuserId: "PorfitListCell")
        
        view.addSubview(tableView)
        addRefresh(scrollView: tableView) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
        }
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        ZMPayManager.shard.payCallBack.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .success:
                self.tableView.mj_header?.beginRefreshing()
            default:
                ZMToast.showToast(title: resp.rawValue)
            }
        }).disposed(by: disposeBag)
        
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .refreshOrderList:
                self.tableView.mj_header?.beginRefreshing()
            default:break
            }
        }).disposed(by: disposeBag)
    }
    
    func loadList() {
        var pa = ["limit" : pageSize, "page" : page, "type" : type.rawValue]
        if status != .all {
            pa["status"] = status.rawValue
        }
        ZMUtil.listRequest(type: MineModels.ProfitList.self, api: MineAPI.profitList(pa)) { resp in
            self.listRequest(resp)
        }
    }
    
    func cancelOrder(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要取消当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.cancelOrder(["id" : id]).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    //  确认收货
    func ensureReceive(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否确认收货", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.suerReceive(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    // 跳转查看物流
    func goExpress(_ orderNo : String) {
        let vc = ZMLogisticsVC()
        vc.orderNo = orderNo
        navigationController?.pushViewController(vc, animated: true)
    }
    
    //  删除订单
    func ensureDelete(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要删除当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.deleteOrder(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    //MARK: --------------------delegate--------------------
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PorfitListCell") as! PorfitListCell
        let data = listData[indexPath.row]
        configData(data: data, indexPath: indexPath, cell: cell)
        return cell
    }
    
    func configData(data: MineModels.ProfitList, indexPath: IndexPath, cell : PorfitListCell) {
        switch type {
            case .recommend: recommendConfig(data: data, indexPath: indexPath, cell: cell)
            case .hammer: fallthrough
            case .redBag: fallthrough
            case .allrich: fallthrough
            case .auction: fallthrough
            case .pool: fallthrough
            case .partner: fallthrough
            case .buySelf: commonConfig(data: data, indexPath: indexPath, cell: cell)
        }
    }
    
    //MARK: 推荐收益 数据配置
    func recommendConfig(data: MineModels.ProfitList, indexPath: IndexPath, cell : PorfitListCell) {
        cell.tbIcon.isHidden = false
        if data.orderType == .phoneCharge {
            cell.img.image = UIImage.init(named: "tele_record")
            cell.tbIcon.image = UIImage.init(named: "phone_icon")
        } else if data.orderType == .signTask {
            cell.img.image = UIImage.init(named: "profit_pool")
            cell.tbIcon.image = UIImage.init(named: "ye_icon")
        } else if data.orderType == .task {
            cell.img.image = UIImage.init(named: "task_icon")
            cell.tbIcon.image = UIImage.init(named: "ye_icon")
        } else if data.orderType == .power {
            cell.img.image = UIImage.init(named: "power_bg")
            cell.tbIcon.image = UIImage.init(named: "power_icon")
        } else if data.orderType == .redBag {
            cell.img.image = UIImage.init(named: "profit_pool")
            cell.tbIcon.image = UIImage.init(named: "red_icon")
        } else if data.orderType == .vipMall {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "icon_512")
        } else if data.orderType == .tb {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "home_bg_icon")
        } else if data.orderType == .mt {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "mt_icon")
        } else if data.orderType == .elem {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "elm_icon")
        } else if type == .auction || data.orderType == .auctionJoin || data.orderType == .auctionRecord || data.orderType == .auctionJoinTeam || type == .hammer {
            if data.image.contains("http") {
                cell.img.zm.setImage(urlStr: data.image)
            } else {
                cell.img.image = UIImage.init(named: "profit_auction")
            }
            cell.tbIcon.image = UIImage.init(named: "action_cell_hammer")
        } else {
            if data.image.contains("http") {
                cell.img.zm.setImage(urlStr: data.image)
            } else {
                cell.img.zm.setImage(urlStr: "https:" + data.image)
            }
            cell.tbIcon.isHidden = true
        }
        
        if type == .recommend {
            var fanStr = "返"
            if data.spreadType == 0 {
                fanStr = "直·返"
            } else if data.spreadType == 1 {
                fanStr = "间·返"
            } else if data.spreadType == 2 {
                fanStr = "团·返"
            }
            cell.fan.text = fanStr
        } else {
            cell.fan.text = "返"
        }
        cell.name.text = data.orderTitle
        cell.orderNo.text = data.orderCreateTime
        
        // 状态显示
        if data.status == .payed {
            cell.state.text = "已付款"
            cell.state.textColor = "#333333".zm.hex()
            cell.tips.text = "订单号：\(data.orderId)"
        } else if data.status == .invalid {
            cell.state.text = "已失效"
            cell.state.textColor = "#999999".zm.hex()
            cell.tips.text = "订单号：\(data.orderId)"
        } else if data.status == .over {
            cell.state.text = "已结算"
            cell.state.textColor = "#999999".zm.hex()
            let text = "结算时间：\(data.settleTime)\n".zm.attributedStr(attrs: [.foregroundColor : "#333333".zm.hex(), .font : UIFont.systemFont(ofSize: 14, weight: .regular)]).zm.append(str: "订单号：\(data.orderId)", attri: ["c" : "#666666", "f" : "12"])
            let pa = NSMutableParagraphStyle()
            pa.lineSpacing = 8
            text.addAttributes([.paragraphStyle : pa], range: NSRange(location: 0, length: text.length))
            cell.tips.attributedText = text
        }
        
        
        if type == .auction || data.orderType == .auctionJoin || data.orderType == .auctionRecord || data.orderType == .auctionJoinTeam || type == .hammer {
            // 竞购相关
            cell.tips.text = "结算时间：\(data.settleTime)"
        }
   
        cell.refundMoney.text = "\(data.income.zm.toString(keep: 4))元"
        cell.setStyle(s: data.status == .invalid ? 1 : 0)
        cell.refundBack.isHidden = ((type == .buySelf && data.income == 0) || type == .hammer)
    }
    
    
    func commonConfig(data: MineModels.ProfitList, indexPath: IndexPath, cell : PorfitListCell) {
        cell.tbIcon.isHidden = false
        if data.orderType == .phoneCharge {
            cell.img.image = UIImage.init(named: "tele_record")
            cell.tbIcon.image = UIImage.init(named: "phone_icon")
        } else if data.orderType == .signTask {
            cell.img.image = UIImage.init(named: "profit_pool")
            cell.tbIcon.image = UIImage.init(named: "ye_icon")
        } else if data.orderType == .task {
            cell.img.image = UIImage.init(named: "task_icon")
            cell.tbIcon.image = UIImage.init(named: "ye_icon")
        } else if data.orderType == .power {
            cell.img.image = UIImage.init(named: "power_bg")
            cell.tbIcon.image = UIImage.init(named: "power_icon")
        } else if data.orderType == .redBag {
            cell.img.image = UIImage.init(named: "profit_pool")
            cell.tbIcon.image = UIImage.init(named: "red_icon")
        } else if data.orderType == .vipMall {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "icon_512")
        } else if data.orderType == .tb {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "home_bg_icon")
        } else if data.orderType == .mt {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "mt_icon")
        } else if data.orderType == .elem {
            cell.img.zm.setImage(urlStr: data.image)
            cell.tbIcon.image = UIImage.init(named: "elm_icon")
        } else if type == .auction || data.orderType == .auctionJoin || data.orderType == .auctionRecord || data.orderType == .auctionJoinTeam || type == .hammer {
            if data.image.contains("http") {
                cell.img.zm.setImage(urlStr: data.image)
            } else {
                cell.img.image = UIImage.init(named: "profit_auction")
            }
            cell.tbIcon.image = UIImage.init(named: "action_cell_hammer")
        } else {
            if data.image.contains("http") {
                cell.img.zm.setImage(urlStr: data.image)
            } else {
                cell.img.zm.setImage(urlStr: "https:" + data.image)
            }
            cell.tbIcon.isHidden = true
        }
        
        if type == .recommend {
            var fanStr = "返"
            if data.spreadType == 0 {
                fanStr = "直·返"
            } else if data.spreadType == 1 {
                fanStr = "间·返"
            } else if data.spreadType == 2 {
                fanStr = "团·返"
            }
            cell.fan.text = fanStr
        } else {
            cell.fan.text = "返"
        }
        cell.name.text = data.orderTitle
        cell.orderNo.text = data.orderCreateTime
        
        // 状态显示
        if data.status == .payed {
            cell.state.text = "已付款"
            cell.state.textColor = "#333333".zm.hex()
            cell.tips.text = "订单号：\(data.orderId)"
        } else if data.status == .invalid {
            cell.state.text = "已失效"
            cell.state.textColor = "#999999".zm.hex()
            cell.tips.text = "订单号：\(data.orderId)"
        } else if data.status == .over {
            cell.state.text = "已结算"
            cell.state.textColor = "#999999".zm.hex()
            let text = "结算时间：\(data.settleTime)\n".zm.attributedStr(attrs: [.foregroundColor : "#333333".zm.hex(), .font : UIFont.systemFont(ofSize: 14, weight: .regular)]).zm.append(str: "订单号：\(data.orderId)", attri: ["c" : "#666666", "f" : "12"])
            let pa = NSMutableParagraphStyle()
            pa.lineSpacing = 8
            text.addAttributes([.paragraphStyle : pa], range: NSRange(location: 0, length: text.length))
            cell.tips.attributedText = text
        }
        
        
        if type == .recommend {
            if type == .auction || data.orderType == .auctionJoin || data.orderType == .auctionRecord || data.orderType == .auctionJoinTeam || type == .hammer {
                // 竞购相关
                cell.tips.text = "结算时间：\(data.settleTime)"
            }
        } else if type == .hammer {
            cell.state.text = "¥\(data.income.zm.toString(keep: 4))"
            cell.state.textColor = Style.mainColor
            cell.tips.text = "结算时间：\(data.settleTime)"
        }
        
        
   
        cell.refundMoney.text = "\(data.income.zm.toString(keep: 4))元"
        cell.setStyle(s: data.status == .invalid ? 1 : 0)
        cell.refundBack.isHidden = ((type == .buySelf && data.income == 0) || type == .hammer)
   
        if type == .pool {
            // 消费分红奖池
            cell.img.image = UIImage.init(named: "profit_pool")
            cell.state.isHidden = true
            cell.tips.text = ""
        } else if type == .auction {
            cell.tips.text = ""
            cell.state.text = ""
        }
    }
    
    
    
    
    
}

